/**
 * Created by chensiwei on 2017-2-7.
 * 引入用例： import baiduMap from 'XXX/js/utils/baidumap'
 * 调用用例： baiduMap.baiduMapLocal().then((data) => {
                 console.log('地址是：', data)
              }).catch((err) => {
                throw err
              })
 * 调用用例： baiduMap.baiduMapAccurate(23.120049110919635, 113.30764967999997).then((data) => {
                 console.log('地址是：', data)
              }).catch((err) => {
                throw err
              })
 *调用用例：baiduMap.deviceLocation().then((data) => {
              console.log('地址是：', data)
            })
 */
import $ from 'jquery'
const key = 'f7GpjqXB2NkRGlzqIqywWTbo'

function baiduMapLocal () {
  // 用百度web api的ip定位城市
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'get',
      url: 'http://api.map.baidu.com/location/ip',
      async: true,
      dataType: 'jsonp',
      jsonp: 'callback',
      data : {
        coor: 'bd09ll',
        ak: key
      }
    }).done((json) => {
      //alert(JSON.stringify(json))
      resolve(json)
    }).fail((error) => {
      reject(error)
    })
  })
}

function baiduMapAccurate (lat, lng) {
  // 用百度经纬度定位具体地址
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'get',
      url: 'http://api.map.baidu.com/geocoder/v2/?output=json&pois=1&ak=' + key + '&location=' + lat + ',' + lng,
      async: true,
      dataType: 'jsonp',
      jsonp: 'callback',
      data : {
      }
    }).done((json) => {
      resolve(json)
    }).fail((error) => {
      reject(error)
    })
  })
}

function deviceLocation () {
  // 用原生浏览器GPS定位换经纬度
  return new Promise((resolve, reject) => {
    if (!window.navigator.geolocation){
      window.alert('您的浏览器不支持定位')
      return
    }
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    }
    function success (position) {
      // 用户允许手机原生GPS定位，用手机获取的经纬度调用百度地图api
      const latitude  = position.coords.latitude
      const longitude = position.coords.longitude
      baiduMapAccurate(latitude, longitude).then((json) => {
        resolve(json)
      }).catch((err) => {
        reject(err)
      })
    }
    function error () {
      // 如果用户禁止手机原生GPS定位，就调用百度的ip定位
      baiduMapLocal().then((data) => {
        baiduMapAccurate(data.content.point.y, data.content.point.x).then((json) => {
          resolve(json)
        }).catch((err) => {
          reject(err)
        })
      })
    }
    window.navigator.geolocation.getCurrentPosition(success, error, options)
  })
}

const newBaiduLocated = () => {
  return new Promise((resolve, reject) => {
    let head= document.getElementsByTagName('head')[0]
    let script= document.createElement('script')
    script.type= 'text/javascript'
    script.onload = () => {
      var geolocation = new BMap.Geolocation()
      //弹出地理授权
      geolocation.getCurrentPosition(function(r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            baiduMapAccurate(r.point.lat, r.point.lng).then((json) => {
              resolve(json)
            }).catch((err) => {
              reject(err)
            })
          } else {
            console.log('定位失败')
          }
        },(error) => {
          console.log('定位失败', error)
          return {
            //设置高精度
            enableHighAccuracy: true
          }
        }
      )
    }
    script.src= `http://api.map.baidu.com/getscript?v=2.0&ak=${key}&services=&t=20170823191629`
    head.appendChild(script)
  })
}
// 将html5定位获得的经纬度转换成百度定位经纬度
const htmlToBaidu = () => {
  // 用原生浏览器GPS定位换经纬度
  return new Promise((resolve, reject) => {
    if (!window.navigator.geolocation){
      window.alert('您的浏览器不支持定位')
      return
    }
    const options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    }
    function success (position) {
      // 用户允许手机原生GPS定位，用手机获取的经纬度调用百度地图api
      const latitude  = position.coords.latitude
      const longitude = position.coords.longitude
      let head= document.getElementsByTagName('head')[0]
      let script= document.createElement('script')
      script.type= 'text/javascript'
      script.onload = () => {
        let head = document.getElementsByTagName('head')[0]
        let script = document.createElement('script')
        script.type = 'text/javascript'
        script.onload = () => {
          var gpsPoint = new BMap.Point(longitude, latitude)
          BMap.Convertor.translate(gpsPoint, 0, function (point) {
            var geoc = new BMap.Geocoder()
            geoc.getLocation(point, function (rs) {
              baiduMapAccurate(rs.point.lat, rs.point.lng).then((json) => {
                resolve(json)
              }).catch((err) => {
                reject(err)
              })
            })
          })
        }
        script.src= 'http://developer.baidu.com/map/jsdemo/demo/convertor.js'
        head.appendChild(script)
      }
      script.src= `http://api.map.baidu.com/getscript?v=2.0&ak=${key}&services=&t=20170823191629`
      head.appendChild(script)
    }
    window.navigator.geolocation.getCurrentPosition(success, newBaiduLocated, options)
  })
}

export {baiduMapLocal, baiduMapAccurate, deviceLocation, htmlToBaidu, newBaiduLocated}
